package com.yuntian.filter;

import com.yuntian.Vo.admin.AdminLoginVo;
import com.yuntian.context.BaseContext;
import com.yuntian.entity.Admin;
import com.yuntian.mapper.AdminMapper;
import com.yuntian.properties.JwtProperties;
import com.yuntian.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AdminMapper adminMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        log.info("请求: {} {}", method, requestURI);

        // 需要放行的路径
        if (shouldSkipFilter(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = request.getHeader(jwtProperties.getAdminTokenName());

        if (token != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            try {
                Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
                Long adminId = Long.valueOf(claims.get("adminId").toString());
                Admin byAdminId = adminMapper.getByAdminId(adminId);
                String adminName = byAdminId.getAdminName();
                String role = byAdminId.getRole();
                log.info("JWT解析成功，管理员ID: {}", adminId);

                // 创建认证对象
                AdminLoginVo adminLoginVo = AdminLoginVo.builder()
                        .adminId(adminId)
                        .adminName(adminName)
                        .role(role)
                        .build();

                log.info("用户 {} 的权限: {}", byAdminId.getAdminName(), adminLoginVo.getAuthorities());
                UsernamePasswordAuthenticationToken authToken =
                        new UsernamePasswordAuthenticationToken(adminLoginVo, null, adminLoginVo.getAuthorities());
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authToken);
                log.info("SecurityContext设置成功");

                BaseContext.setCurrentId(adminId);

            } catch (Exception e) {
                log.error("JWT解析失败: {}", e.getMessage(), e);
            }
        } else if (token == null) {
            log.warn("请求头中没有找到token");
        } else {
            log.info("SecurityContext中已存在认证信息");
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 判断是否需要跳过过滤器
     */
    private boolean shouldSkipFilter(String requestURI) {
        // 登录和注册接口
        if (requestURI.equals("/admin/login") || requestURI.equals("/admin/register")) {
            return true;
        }
        if (requestURI.equals("/user/user/login") || requestURI.equals("/user/user/register")) {
            return true;
        }


        // 静态资源
        if (requestURI.startsWith("/static/") ||
                requestURI.startsWith("/css/") ||
                requestURI.startsWith("/js/") ||
                requestURI.startsWith("/images/")) {
            return true;
        }

        // 健康检查等
        if (requestURI.equals("/actuator/health") ||
                requestURI.equals("/favicon.ico")) {
            return true;
        }

        return false;
    }
}